function vpitch = expan_pitch_autolag(signal, fs,ethh, window, hop,m)

% EXPAN_PITCH
%   EXPAN_PITCH_AUTOCORR(SIGNAL, FS, WINDOW, HOP) calcula o pitch do sinal 
%   SIGNAL cuja frequencia de amostragem � FS, utilizando uma janela de
%   tamanho WINDOW e salto de tamanho HOP.

fprintf(1, 'Estimando o pitch do sinal por autocorrelação...\n');

nsamples = 13;   % N�mero de amostras para a moda (utilizar n�mero �mpar)

len=length(signal);                 % Tamanho do sinal
num_quadros = (len-window)/hop;    % N�mero de quadros do sinal
half = floor(window/2);             % Metade do tamanho da janela
shift = 512;


% In�cio do sinal

for i=1:half/hop   
    %---------poltar autocor de janela-----
    eth = 0;
    if i == ethh 
       eth = 1;
    end   
    %---------------------------------------
    frame = signal(1:(i-1)*hop+half);  
    pitch(i) = expan_frame_pitch_autocorr(frame, fs, eth);
end   

% Meio do sinal
for i=half/hop+1:floor((len-half)/hop)
    
    %---------poltar autocor de janela-----
    eth = 0;
    if i == ethh 
       eth = 1;
    end
    %---------------------------------------
    if (i-1)*hop-half < shift
       frame = signal((i-1)*hop-half+1:(i-1)*hop+half);
       pitch(i) = expan_frame_pitch_autocorr(frame, fs, eth);
    else    
       frame = signal((i-1)*hop-half+1:(i-1)*hop+half);
       lag = signal(((i-1)*hop-half+1)-shift:((i-1)*hop-half));
       pitch(i) = expan_frame_pitch_autolag(frame, fs,lag, eth);
    end
    
  
end

% Final do sinal
for i=floor((len-half)/hop)+1:ceil(len/hop)
    
    %---------poltar autocor de janela-----
    eth = 0;
    if i == ethh 
       eth = 1;
    end
    %---------------------------------------
    
    if ((i-1)*hop+half < len)
        
        frame = signal((i-1)*hop-half+1:(i-1)*hop+half);
    else
       
        frame = signal((i-1)*hop-half+1:end);
    end
    
    pitch(i) = expan_frame_pitch_autocorr(frame, fs, eth);
end

vpitch = pitch;

%---- C�lculo da moda ----%

if m == 1
   
    % Primeiros frames
    for i=1:((nsamples-1)/2)
        vpitch(i) = pitch(i);
    end

    % Frames intermediarios
    for i=((nsamples-1)/2 + 1):length(pitch)-((nsamples-1)/2)
        vpitch(i) = mode(pitch(i+[-(nsamples-1)/2:(nsamples-1)/2]));
    end

    % Frames finais
    for i=(length(pitch)-((nsamples-1)/2)):length(pitch)
       vpitch(i) = pitch(i); 
    end

end